package com.itheima.controller;

import com.itheima.Service.CategoryService;
import com.itheima.pojo.Category;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 获取商品分类列表
     */
    @GetMapping
    public Result list(Category category) {
        log.info("获取商品分类列表{}",category);
        PageResult<Category> categories = categoryService.list(category);
        return Result.success(categories);
    }

    /**
     * 根据ID获取分类
     * @param id 分类ID
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {  // 路径变量类型改为 Integer
        log.info("获取分类，ID：{}", id);
        Category category = categoryService.getById(id);
        return Result.success(category);
    }

    /**
     * 新增分类
     * @param category 分类对象
     */
    @PostMapping
    public Result add(@RequestBody Category category) {
        log.info("新增分类：{}", category);
        categoryService.add(category);
        return Result.success();
    }

    /**
     * 更新分类
     * @param category 分类对象
     */
    @PutMapping
    public Result update(@RequestBody Category category) {
        log.info("更新分类：{}", category);
        categoryService.update(category);
        return Result.success();
    }

    /**
     * 删除分类
     * @param id 分类ID
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {  // 路径变量类型改为 Integer
        log.info("删除分类，ID：{}", id);
        try {
            categoryService.deleteById(id);
        } catch (Exception e) {
            return Result.error("该分类下还有商品，请先删除商品！");
        }
        return Result.success();
    }

    @GetMapping("/user")
    public Result selectfenlei(){
        List<Category> categoryList=categoryService.fenleilist();
        return Result.success(categoryList);
    }
}